package org.fuxia.im.core.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.entries.ECResponse;
import org.fuxia.im.core.entries.ECSession;
import org.fuxia.im.core.server.ECSessionMananger;
import org.fuxia.im.core.socket.impl.ECNioServer;
import org.fuxia.im.core.utils.ObjectUtil;
import org.fuxia.im.db.dao.UserDaoImpl;
import org.fuxia.im.db.dao.UserFriendDaoImpl;
import org.fuxia.im.entities.User;
import org.fuxia.im.entities.UserFriend;

import com.alibaba.fastjson.JSONArray;


public class UserFriendService extends AbstractService {

	@Resource
	private UserDaoImpl userDao ;
	@Resource
	private UserFriendDaoImpl userFriendDao ;
	
	@SuppressWarnings("rawtypes")
	private List result = null ;
	
	
	public void service(ECPacket packet) {
		String option = packet.getParameter("option") ;
		System.out.println(option);
		if("addFriend".equals(option)) {
			addFriend(packet) ;
		}else if("moveFriend".equals(option)) {
			moveFriend(packet) ;
		}
	}
	
	/**
	 * 添加好友
	 * @param packet
	 */
	public void addFriend(ECPacket packet) {
		ECResponse respCurrent = new ECResponse() ;
		respCurrent.setResponseType("ADD_FRIEND") ;
		
		String from = packet.getFrom() ;
		String to = packet.getTo() ;
		

		
		UserFriend userFriend = new UserFriend() ;
		String groupId = packet.getParameter("groupId") ;
		String groupName = packet.getParameter("groupName") ;
		String remarkName = packet.getParameter("remarkName") ;
		String userName = packet.getParameter("userName") ;
		int status = Integer.parseInt(packet.getParameter("status")) ;
		
		userFriend.setGroupId(groupId) ;
		userFriend.setGroupName(groupName) ;
		if("".equals(remarkName)){
			remarkName = userName ;
		}
		userFriend.setNickName(remarkName) ;
		userFriend.setOrignUserCode(from) ;
		userFriend.setFriendUserCode(to) ;

		try{
			userFriendDao.save(userFriend) ;
			respCurrent.setStatusCode(200) ;
			respCurrent.put("groupKey", groupId+"#"+groupName) ;
			respCurrent.put("remark", remarkName) ;
			respCurrent.put("user", getByUserCode(to)) ;
			respCurrent.setResponseText("您已成功添加("+to+")为好友!") ;
			try{
				//提示被添加好友，有人将其加为好友
				//String hql = "select imagePath,nickName,userCode,sex,age,address from IMUser where userCode=?" ;
				ECPacket packetFriend = new ECPacket() ;
				Object[] temp = (Object[]) getByUserCode(from) ;
				if(temp[7] == null) {
					temp[7] = "男" ;
				}
				if(temp[5] == null) {
					temp[5] = "0" ;
				}
				if(temp[6] == null) {
					temp[5] = "" ;
				}
				packetFriend.setMessageType("receiveAdd") ;
				packetFriend.addParam("node", "【"+from+"】通过'查找账号'添加您为好友。") ;
				packetFriend.addParam("status", Integer.toString((status+1))) ;
				packetFriend.addParam("iamgePath", temp[4].toString()) ;
				packetFriend.addParam("nickName", temp[1].toString()) ;
				packetFriend.addParam("userCode", temp[0].toString()) ;
				packetFriend.addParam("sex", temp[7].toString()) ;
				packetFriend.addParam("age", temp[5].toString()) ;
				packetFriend.addParam("address", temp[6].toString()) ;
				packetFriend.setFrom(from) ;
				packetFriend.setTo(to) ;
				ECSession sessionFriend = ECSessionMananger.getInstance().getUserSession(to) ;
				if(sessionFriend != null) {
					ECNioServer.sendPacket(packetFriend, sessionFriend.getChannel()) ;
				}else{
					ECSessionMananger.getInstance().putOfflineMessage(packetFriend) ;
				}
			}catch(Exception e) {
				e.printStackTrace() ;
			}
		}catch(Exception e) {
					e.printStackTrace() ;
					respCurrent.setStatusCode(400) ;
					respCurrent.setResponseText("添加好友失败") ;
		}
		try {
			ECSession session = ECSessionMananger.getInstance().getUserSession(from) ;
			ECNioServer.writeResponse(respCurrent, session.getChannel()) ;
		}catch(Exception e) {
			e.printStackTrace() ;
		}
	}
	
	
	/**
	 * 将好友从一个分组移动到另外一个分组
	 * @param packet
	 */
	public void moveFriend(ECPacket packet){
		
		ECResponse resp = new ECResponse() ;
		resp.setResponseType("moveFriend") ;
		
		String groupId = packet.getParameter("groupId") ;
		String groupName = packet.getParameter("groupName") ;
		String from = packet.getFrom() ;
		String to = packet.getTo() ;
		System.out.println(to);
		String friendNickName = packet.getParameter("friendNickName") ;
		Object[] userFriend = null ;
		String id = "";
		String hql = "select uf.id,uf.friendUserCode,uf.groupId,uf.groupName,uf.nickName,uf.orignUserCode from UserFriend uf where uf.friendUserCode=? and uf.orignUserCode=?" ;
		try{
			List userFriends= userFriendDao.find(hql, new String[]{to, from}) ;
			if(userFriends.size()>0) {
				userFriend = (Object[])userFriends.get(0) ;
				id = userFriend[0].toString() ;
				System.out.println(userFriend[2].toString() );
				System.out.println(userFriend[3].toString() );
				
			}
		}catch(Exception e) {
			e.printStackTrace() ;
		}
		UserFriend uf = new UserFriend() ;
		uf.setFriendUserCode(to) ;
		uf.setOrignUserCode(from) ;
		uf.setGroupId(groupId) ;
		uf.setGroupName(groupName) ;
		uf.setNickName(friendNickName) ;
		uf.setId(id) ;
		
		try{
			
			userFriendDao.merge(uf) ;
			Object user1 = null;
			String hql1 = "select user.userCode,uf.nickName,user.personNote,user.userState,"
						+ "user.imagePath,user.age,user.address,user.sex from IMUser user, UserFriend uf"
						+ " where user.userCode=uf.friendUserCode and groupId=? and uf.friendUserCode=?" ;
			
			List users = userFriendDao.find(hql1, new String[]{groupId, to}) ;
			if(users.size() > 0) {
				user1 = users.get(0) ;
				System.out.println(user1);
			}
			
			resp.setStatusCode(200) ;
			resp.put("user", user1) ;
			resp.put("oldGroupKey", userFriend[2].toString()+"#"+userFriend[3].toString()) ;
			resp.put("newGroupKey", groupId+"#"+groupName) ;
		}catch(Exception e) {
			e.printStackTrace() ;
			resp.setStatusCode(400) ;
			resp.setResponseText("移动好友失败") ;
		}
		
		
		try {
			ECSession session = ECSessionMananger.getInstance().getUserSession(from) ;
			ECNioServer.writeResponse(resp, session.getChannel()) ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	public Object getByUserCode(String userCode) { 

		Object userInfo = null ; 
		String hql = "select user.userCode,user.nickName,user.personNote,user.userState,"
				+ "user.imagePath,user.age,user.address,user.sex "
				+ "from IMUser user where "
				+ " user.userCode=?" ;
		System.out.println(hql);
		try{
			result = userDao.find(hql, new String[]{userCode});
			if(result.size()>0) {
				userInfo = result.get(0) ;
			}
			
		}catch(Exception e) {
			e.printStackTrace() ;
		}
		return userInfo ;
	}
	
}
